package com.codejie.pms.controller;

import com.codejie.pms.entity.*;
import com.codejie.pms.service.ModelManagerService;
import com.codejie.pms.service.StaffKpiService;
import com.codejie.pms.util.DateUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;

@Controller
@Data
@Slf4j
public class ModelManagerController {

    @Autowired
    private ModelManagerService modelManagerService;
    @Autowired
    private StaffKpiService staffKpiService;

    /**
     * Description 所有项目信息
     */
    @RequestMapping("manager/all_msg")
    public String projectList(Model model) {
        List<Project> project = modelManagerService.projectList();
        model.addAttribute("project", project);
        return "manager/all_msg";
    }

    //进入添加项目信息页面
    @GetMapping("/add")
    public String addProject() {
        return "manager/addProject";
    }

    //添加项目信息
    @PostMapping("/add")
    public String addProject(Project project) {
        modelManagerService.addProject(project);
        return "redirect:manager/all_msg";
    }

    /**
     * 获取员工修改页面，返回通过ID获取到的员工信息
     *
     * @param id
     * @param model
     * @return
     */
    @GetMapping("/updateProject/{proId}")
    public String getUpdatePage(@PathVariable("proId") String id, Model model) {
        Project project = modelManagerService.selectByproId(id);
        System.out.println(project);
        model.addAttribute("pro", project);
        System.out.println(model);
        return "manager/updateProject";
    }

    /**
     * 通过员工id删除员工
     *
     * @param id
     * @return
     */
    @GetMapping("/delete/{proId}")
    public String deleteMethod(@PathVariable("proId") String id) {
        modelManagerService.deleteByproId(id);
        return "redirect:/manager/all_msg";
    }

    /**
     * 通过项目id修改信息
     */
    @PostMapping("/update")
    public String updateMethod(Project project) {
        System.out.println("project.getProId()");
        modelManagerService.updateByproId(project);
        return "redirect:manager/all_msg";
    }

    //按项目编号查询
    @PostMapping("/searchproid")
    public String searchMethod(String proId, Model model) {
        Project project = modelManagerService.selectByproId(proId);
        model.addAttribute("project", project);
        System.out.printf(proId);
        return "manager/all_msg";
    }

    //进入分配人员界面
    @GetMapping("/distribution/{proId}")
    public String enterdistribution(@PathVariable("proId") String id, StaffKpi staffKpi, Model model) {
        Project project = modelManagerService.selectByproId(id);
        System.out.println(project);
        model.addAttribute("pro", project);
        return "manager/distri_staff";
    }

    //分配员工项目
    @PostMapping("/distri")
    public String distribution(StaffKpi staffKpi) {
        staffKpiService.addStaffKpi(staffKpi);
        return "redirect:manager/all_msg";
    }

    //进入审核员工界面
    @RequestMapping("manager/staff_pro")
    public String staff(Model model) {
        //List<Staff> staff =modelManagerService.staffByModel();
        List<StaffKpi> staffKpis = modelManagerService.checkstaff();
        model.addAttribute("staffKpis", staffKpis);
        return "manager/staff_pro";
    }

    //进入审核员工界面
    @RequestMapping("/login")
    public String xiu(Model model) {
        return "/login";
    }

    //文件上传
    @PostMapping("/upload")
    public String upload(@RequestParam("file") MultipartFile file) {
        try {
            if (file.isEmpty()) {
                return "文件为空";
            }
            System.out.println("hhh");
            //获取文件名
            String fileName = file.getOriginalFilename();
            log.info("上传的文件名：" + fileName);
            //获取文件后缀名
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            log.info("文件后缀名：" + suffixName);
            //设置文件存储路径
            String filePath = "D:/房地产项目/upload/";
            String path = filePath + fileName;
            File dest = new File(path);
            //检测是否存在该目录
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            //写入文件
            file.transferTo(dest);
            return "redirect:manager/all_msg";
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "上传失败";
    }

    @PostMapping("/download")
    public String downloadFile(@RequestParam("file") MultipartFile file) {
        try {
            if (file.isEmpty()) {
                return "文件为空";
            }
            System.out.println("hhh");
            //获取文件名
            String fileName = file.getOriginalFilename();
            log.info("上传的文件名：" + fileName);
            //获取文件后缀名
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            log.info("文件后缀名：" + suffixName);
            //设置文件存储路径
            String filePath = "D:/房地产项目/download/";
            String path = filePath + fileName;
            File dest = new File(path);
            //检测是否存在该目录
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            //写入文件
            file.transferTo(dest);
            return "redirect:manager/staff_pro";
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "下载失败";
    }

    //以execl导出项目列表
    @RequestMapping(value = "/pro/export")
    public void exportallDocumentaryExcel(HttpServletResponse response) throws IOException {
        try {
//            List<Staff> staffList = staffService.selectStaffList();
            List<Project> projectList = modelManagerService.projectList();
            // 在内存中创建一个Excel文件，通过输出流写到员工端提供下载
            // 内存中保留 10000 条数据，以免内存溢出，其余写入 硬盘
            SXSSFWorkbook workbook = new SXSSFWorkbook(10000);
            CellStyle style = workbook.createCellStyle();
            style.setAlignment(XSSFCellStyle.ALIGN_CENTER);//SXSSFWorkbook方式的居中
            // 创建一个sheet页
            SXSSFSheet sheet = (SXSSFSheet) workbook.createSheet("表格");
            // 分别设置Excel列的宽度

            for (int i = 0; i < 10; i++) {
                sheet.setColumnWidth(i, 4000);
            }
            // 创建标题
            SXSSFRow headRow = (SXSSFRow) sheet.createRow(0);
            headRow.createCell(0).setCellValue("项目编号");
            headRow.createCell(1).setCellValue("项目开始时间");
            headRow.createCell(2).setCellValue("项目名称");
            headRow.createCell(3).setCellValue("项目结束时间");
            headRow.createCell(4).setCellValue("项目类型");
            headRow.createCell(5).setCellValue("模型主管");
            headRow.createCell(6).setCellValue("渲染主管");
            headRow.createCell(7).setCellValue("后期主管");
            headRow.createCell(8).setCellValue("项目状态");

            for (Project project : projectList) {
                // 创建行
                SXSSFRow dataRow = (SXSSFRow) sheet.createRow(sheet.getLastRowNum() + 1);

                dataRow.createCell(0).setCellValue(project.getProId());
                dataRow.createCell(1).setCellValue(project.getProStartTime());
                dataRow.createCell(2).setCellValue(project.getProName());
                dataRow.createCell(3).setCellValue(project.getProEndTime());
                dataRow.createCell(4).setCellValue(project.getProType());
                dataRow.createCell(5).setCellValue(project.getModelManager());
                dataRow.createCell(6).setCellValue(project.getDrawManager());
                dataRow.createCell(7).setCellValue(project.getLaterManager());
                dataRow.createCell(8).setCellValue(project.getProState());
            }

            // 设置Excel文件名，并以中文进行编码
            String codedFileName = new String("员工列表".getBytes("gbk"), "iso-8859-1");
            response.setHeader("Content-Disposition", "attachment;filename="
                    + codedFileName + DateUtil.getCurrentTime2()
                    + ".xlsx");
            // 响应类型,编码
            response.setContentType("application/octet-stream;charset=UTF-8");
            // 形成输出流
            OutputStream osOut = response.getOutputStream();
            // 将指定的字节写入此输出流
            workbook.write(osOut);
            // 刷新此输出流并强制将所有缓冲的输出字节被写出
            osOut.flush();
            // 关闭流
            osOut.close();
            /*
             * dispose of temporary files backing this workbook on disk
             * 处理在磁盘上备份此工作簿的临时文件 SXSSF分配临时文件，必须始终清除显式，通过调用dispose方法
             */
            workbook.dispose();

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("导出员工失败！失败信息：" + e.getMessage());
        }
    }


    @GetMapping("/advice/{staffId}")
    public String ad(@PathVariable("staffId") String id, Model model) {
        StaffKpi staffKpi = modelManagerService.adviceby(id);
        model.addAttribute("sta", staffKpi);
        return "/manager/advice";
    }

    //添加项目信息
    @PostMapping("/ad")
    public String advice(StaffKpi staffKpi) {
        modelManagerService.updateAdvice(staffKpi);
        System.out.println(staffKpi.getAdvice());
        return "redirect:manager/staff_pro";
    }


}
